﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using personalplaner.business;
using personalplaner.business.enums;
using personalplaner.business.stamm;
using personalplaner.common.mvvm;
using personalplaner.common.mvvm.commands;
using personalplaner.gui.stamm.views;
using personalplaner.gui.stamm.windows;
using personalplaner.servicemodel.common;
using personalplaner.servicemodel.dataaccess;

namespace personalplaner.gui.stamm.viewmodels
{
	public class PlanungsJahrStammViewModel : BaseViewModel
	{
		public PlanungsJahrStammViewModel(DependencyObject parent)
			: base(parent)
		{
		}

		public override void Loaded()
		{
			var mw = GetService<IMainWindowDisplayContainer>();
			mw.IsWaitVisible = false;

            IsOldYear = true;
		}

		#region Commands

        ICommand _newcommand;
        public ICommand NewCommand
        {
            get
            {
                if (_newcommand == null)
                    _newcommand = new RelayCommand(OnNew);
                return _newcommand;
            }
        }

        private void OnNew(object parameter)
        {
            IsOldYear = false;
        }

		ICommand _okcommand;
		public ICommand OkCommand
		{
			get
			{
				if (_okcommand == null)
					_okcommand = new RelayCommand(OnOkCommand);
				return _okcommand;
			}
		}

		private void OnOkCommand(object parameter)
		{
			var wnd = Parent as Window;
			if (wnd != null)
			{
				wnd.DialogResult = true;
				wnd.Close();
				return;
			}

			var mw = GetService<IMainWindowDisplayContainer>();
			mw.MoveToPreviousView();
		}

		ICommand _cancelcommand;
		public ICommand CancelCommand
		{
			get
			{
				if (_cancelcommand == null)
					_cancelcommand = new RelayCommand(OnCancelCommand);
				return _cancelcommand;
			}
		}

		private void OnCancelCommand(object parameter)
		{
			var wnd = Parent as Window;
			if (wnd != null)
			{
				wnd.DialogResult = false;
				wnd.Close();
				return;
			}

			var mw = GetService<IMainWindowDisplayContainer>();
			mw.MoveToPreviousView();
		}

		ICommand _createYearcommand;
		public ICommand CreateYearCommand
		{
			get
			{
                if (_createYearcommand == null)
                    _createYearcommand = new RelayCommand(OnCreateYear, p => !IsOldYear);
				return _createYearcommand;
			}
		}

        private void OnCreateYear(object parameter)
        {
            if (MessageBox.Show(Window.GetWindow(Parent), Properties.Resources.CreateNewYearDeactivateOldYear,
                Properties.Resources.CreateYear,
                MessageBoxButton.YesNo,
                MessageBoxImage.Exclamation) == MessageBoxResult.No)
                return;

            var mw = GetService<IMainWindowDisplayContainer>();
            mw.IsWaitVisible = true;

            var da = GetService<ICommonDataAccess>();
            int oldyearid = da.GetActiveJahrId();

            da.CreateNewYear(SelectedYear);

            if (oldyearid > 0)
                da.SetPersonZeiten(oldyearid);

            var yearhelper = new InitSettingsHelper(personalplaner.common.SettingsProvider.Settings);
            personalplaner.common.SettingsProvider.Settings.Year = yearhelper.GetActiveYear();
            personalplaner.common.SettingsProvider.Settings.YearId = yearhelper.GetActiveYearId();

            _existingYears = null;
            RaisePropertyChanged("ExistingYears");
            _years = null;
            RaisePropertyChanged("Years");

            IsOldYear = true;
            //try
            //{
            //    SelectedExistingYear = (from a in ExistingYears where a.Status == enStatus.Active select a).FirstOrDefault();
            //}
            //catch { }

            mw.IsWaitVisible = false;

            if (MessageBox.Show(Window.GetWindow(Parent), Properties.Resources.EditMonthsAfterCreateYear, Properties.Resources.DaysPerMonth, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                OnMonth(null);
        }

		ICommand _activateYearCommand;
		public ICommand ActivateYearCommand
		{
			get
			{
				if (_activateYearCommand == null)
					_activateYearCommand = new RelayCommand(OnActivateYear, CanActivateOldYear);
				return _activateYearCommand;
			}
		}

		private void OnActivateYear(object parameter)
		{
			var da = GetService<ICommonDataAccess>();
			da.ReactivateYear(SelectedYear);

            _existingYears = null;
            RaisePropertyChanged("ExistingYears");
            _years = null;
            RaisePropertyChanged("Years");
		}

		private bool CanActivateOldYear(object param)
		{
			if (ExistingYears != null && YearExists(SelectedYear) && SelectedExistingYear != null && SelectedExistingYear.Status == business.enums.enStatus.Inactive)
				return true;

			return false;
		}

        ICommand _monthCommand;
        public ICommand MonthCommand
        {
            get
            {
                if (_monthCommand == null)
                    _monthCommand = new RelayCommand(OnMonth, p => SelectedExistingYear != null && !SelectedExistingYear.IsNew);
                return _monthCommand;
            }
        }

        private void OnMonth(object parameter)
        {
            var dlg = new EditDaysInMonth()
            {
                Owner = Window.GetWindow(Parent)
            };

            dlg.ShowDialog();
        }

        ICommand _feiertageCommand;
        public ICommand FeiertageCommand
        {
            get
            {
                if (_feiertageCommand == null)
                    _feiertageCommand = new RelayCommand(OnFeiertage, p => SelectedExistingYear != null && !SelectedExistingYear.IsNew);
                return _feiertageCommand;
            }
        }

        private void OnFeiertage(object parameter)
        {
            var service = GetService<IMainWindowDisplayContainer>();

            if (service.ContainesItem(enDisplayItemType.FeiertageStamm))
                service.SelectItem(enDisplayItemType.FeiertageStamm);
            else
                service.AddSimpleContentItem(enDisplayItemType.FeiertageStamm, new FeiertageStamm());
        }

		#endregion

		private bool YearExists(int year)
		{
            if (ExistingYears == null)
				return false;

			if ((from a in ExistingYears where a.Jahr == year select a).ToList().Count > 0)
				return true;

			return false;
		}

		#region Properties

		IList<int> _years;
		public IList<int> Years
		{
			get
			{
				if (_years == null)
				{
					_years = new List<int>();

					int maxJahr = DateTime.Now.Year;
					int cnt = 0;
					while (cnt < 10)
					{
						if (!YearExists(maxJahr))
						{
							_years.Add(maxJahr);
							cnt++;
						}
                        maxJahr++;
					}

                    if (!IsOldYear)
                        SelectedYear = Years[0];
				}
				return _years;
			}
		}

		int _selectedYear;
		public int SelectedYear
		{
			get
			{
				return _selectedYear;
			}
			set
			{
				_selectedYear = value;
				RaisePropertyChanged("SelectedYear");

				RaisePropertyChanged("Von");
				RaisePropertyChanged("Bis");
			}
		}

        int _selectedYearIndex;
        public int SelectedYearIndex
        {
            get
            {
                return _selectedYearIndex;
            }
            set
            {
                _selectedYearIndex = value;
                RaisePropertyChanged("SelectedYearIndex");
            }
        }

		public DateTime? Von
		{
			get
			{
				if (SelectedYear < 1000)
					return null;
				return new DateTime(SelectedYear, 1, 1);
			}
		}

		public DateTime? Bis
		{
			get
			{
				if (SelectedYear < 1000)
					return null;
				return new DateTime(SelectedYear, 12, 31);
			}
		}

		bool _isOldYear;
		public bool IsOldYear
		{
			get { return _isOldYear; }
			set
			{
				if(value && ExistingYears.Count<=0)
					value=false;

				_isOldYear = value;
				RaisePropertyChanged("IsOldYear");

                if (value)
                {
                    SelectedExistingYear = (from a in ExistingYears where a.Status == business.enums.enStatus.Active select a).FirstOrDefault();
                    SelectedYearIndex = -1;
                    //SelectedYear = SelectedExistingYear.Von.Year;
                }
                else
                {
                    SelectedExistingYear = null;
                    SelectedYear = Years[0];
                }
			}
		}

		IList<PlanYear> _existingYears;
		public IList<PlanYear> ExistingYears
		{
			get
			{
				if (_existingYears == null)
				{
					var da = GetService<ICommonDataAccess>();
					var lst = da.GetActiveYears();
					_existingYears = lst != null ? new ObservableCollection<PlanYear>(lst) : new ObservableCollection<PlanYear>();
				}
				return _existingYears;
			}
		}

		PlanYear _selectedExistingYear;
		public PlanYear SelectedExistingYear
		{
			get
			{
				return _selectedExistingYear;
			}
			set
			{
				_selectedExistingYear = value;
				RaisePropertyChanged("SelectedExistingYear");

				if (value != null)
					SelectedYear = value.Von.Year;
			}
		}


		//IList<ArbeitsPlanHeader> _arbeitsplanlist;
		//public IList<ArbeitsPlanHeader> ArbeitsPlanList
		//{
		//    get
		//    {
		//        if (Designer.IsDesignMode)
		//            return new ObservableCollection<ArbeitsPlanHeader>();

		//        if (_arbeitsplanlist == null)
		//        {
		//            var da = GetService<IPlanDataAccess>();
		//            var lst = da.GetArbeitsPlaene(false);
		//            _arbeitsplanlist = lst != null ? new ObservableCollection<ArbeitsPlanHeader>(lst.OrderByDescending(a => a.PlanId)) : new ObservableCollection<ArbeitsPlanHeader>();
		//        }
		//        return _arbeitsplanlist;
		//    }
		//}

		//ArbeitsPlanHeader _selectedArbeitsPlan;
		//public ArbeitsPlanHeader SelectedArbeitsPlan
		//{
		//    get { return _selectedArbeitsPlan; }
		//    set
		//    {
		//        _selectedArbeitsPlan = value;
		//        RaisePropertyChanged("SelectedArbeitsPlan");
		//    }
		//}

		#endregion
	}
}
